<template>

	<view>
		<uni-popup ref="upgradeDialog" type="dialog" :isMaskClick="false">
			<uni-popup-dialog type="info" cancelText="关闭APP" confirmText="升级" title="通知" content="有新版本需要更新"
				@confirm="confirmUpgrade" @close="closeApp"></uni-popup-dialog>
		</uni-popup>

		<!-- 更新版本进度-->
		<view>
			<uni-popup ref="upgradeProcessPopup" type="share" :isMaskClick="false">
				<view style="background:white;padding:0 20px;">
					<view style="text-align: center;padding:10px 0;">{{download_tips_text}}</view>
					<view style="padding:20px 0 40px;">
						<progress :percent="downloadProcess" stroke-width="3" />
					</view>
					<view v-if="download_success_status" style="padding-bottom:10px;">
						<button type="primary" @click="installPackage">{{$t("upgrade.install")}}</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>

</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue'


	const upgradeDialog = ref(null);
	const upgradeProcessPopup = ref(null);

	const download_tips_text = ref("正在下载请勿关闭");
	const downloadProcess = ref(0); // 下载进度条
	const download_success_status = ref(false); // 是否下载完成
	
	let app_download_url = ""; // 安装包的下载路径
	let downloadInstance = null; // 本次下载的实例
	let temp_file_path = ""; // 临时的文件路径
	const localFilePathKey = ref("/"); // 本地保存的地址


	onMounted(() => {
		checkVersionUpgrade();
	})

	// 检查版本更新
	const checkVersionUpgrade = () => {
		let current_version = "";

		// #ifdef APP
		const systemInfo = uni.getSystemInfoSync();
		current_version = systemInfo.appWgtVersion;
		appVersion(current_version);
		// #endif
	}

	// 这里去获取最新app的信息
	const appVersion = (current_version) => {

		let url = "http://1.0.1.apk";
		let new_version = "1.0.1";

		if (compareVersions(new_version, current_version) == 1) {
			app_download_url = url;
			upgradeDialog.value.open();
		}
	}

	const confirmUpgrade = () => {
		if (!app_download_url) {
			uni.showToast({
				title: "APP下载路径缺失",
				icon: 'none',
				duration: 1500
			})
			return;
		}

		upgradeProcessPopup.value.open();
		// 开始下载包
		downloadInstance = uni.downloadFile({
			url: app_download_url,
			success: (res) => {
				if (res.statusCode == 200) {
					temp_file_path = res.tempFilePath;

					download_tips_text.value = "正在安装";

					installPackage();
				} else {
					uni.showToast({
						title: "下载失败",
						icon: "error"
					})
				}
			},
			fail(err) {
				uni.showToast({
					title: err,
					icon: "error"
				});
			}
		});

		// 监听进度
		downloadInstance.onProgressUpdate((res) => {
			downloadProcess.value = res.progress;
		})

	}
	
	const installPackage = () => {
		download_success_status.value = true;
	
		plus.runtime.install(temp_file_path, {
			force: true // 是否强制更新
		}, async res => {
			const localFilePathRecord = uni.getStorageSync(localFilePathKey);
	
			uni.setStorageSync(localFilePathKey, {
				...localFilePathRecord,
				installed: true
			});
	
		}, async error => {
			uni.showModal({
				title: "更新失败",
				content: "请稍后重试或联系工作人员",
				showCancel: false,
			})
		})
	}

	const closeApp = () => {
		// 关闭app
		plus.runtime.quit();
	}

	const compareVersions = (v1, v2) => {
		// 将版本号拆分为数字数组
		const parts1 = v1.split('.').map(Number);
		const parts2 = v2.split('.').map(Number);

		// 获取最大层级深度
		const maxLength = Math.max(parts1.length, parts2.length);

		for (let i = 0; i < maxLength; i++) {
			// 获取当前层级的数字（不存在则视为0）
			const num1 = parts1[i] || 0;
			const num2 = parts2[i] || 0;

			// 比较当前层级
			if (num1 > num2) return 1; // v1 > v2
			if (num1 < num2) return -1; // v1 < v2
		}

		return 0; // 版本号相等
	}
</script>

<style>
</style>